import { t } from 'i18next'
import {
	Wrap,
	StyledWrap,
	IconHelper,
	IconModalRemove,
	HelpWrap,
	ScrollBtn,
	ScrollWrap,
	BodyWrap,
	StyledRequestTip,
	IconClose,
} from './style'
import { TabItem } from './interface'
import { useInterval, useRequest } from 'ahooks'
import { SystemInfo } from './blocks/systemInfo'
import { Checking } from './blocks/checking'
import { useData } from './blocks/checking/hooks'
import { useMccStore } from '../../store'
import { useMsgStore } from './store'
import shallow from 'zustand/shallow'
import { useGlobalStore } from '@/store/global'
import { useEffect, useRef, useState } from 'react'
import { Modal } from '@kedacom/react-next'
import { Apply } from './blocks/apply'
import { fetchApplyMsg } from '@/api/manager/helper'
const Helper = () => {
	const ref = useRef(null)
	const { sysMessage, msgCache, handleShow, showHelper, update, tab, showApplyTip, applyList } = useMsgStore(
		(state) => ({
			handleShow: state.handleShow,
			sysMessage: state.sysMessage,
			showHelper: state.showHelper,
			update: state.update,
			tab: state.tab,
			msgCache: state.msgCache,
			showApplyTip: state.showApplyTip,
			applyList: state.applyList,
		}),
		shallow
	)
	/** 上下按钮是否置灰 */
	const [disable, setDisable] = useState({
		pre: false,
		next: false,
	})
	const { meetingMoid, isExitChecking, meetingType } = useMccStore(
		(state) => ({
			isExitChecking: state.enableJdb === 1,
			meetingMoid: state.mccInfo.meetingMoid,
			meetingType: state.mccInfo.meetingType,
		}),
		shallow
	)
	const SWITCH = useGlobalStore((state) => state.SWITCH)

	const checkingService = useData()

	const { loading, data } = useRequest(() => fetchApplyMsg(meetingMoid, { state: 1 }))
	useEffect(() => {
		if (!loading && data) {
			update({
				showApplyTip: data.length > 0,
				applyList: data,
				innerApplyList: data.map((i) => ({ ...i, done: false })),
			})
		}
	}, [data, loading])

	useEffect(() => {
		let data: TabItem[] = [
			{ name: 'apply', label: t('审批终端申请') },
			{ name: 'checking', label: t('检测终端') },
			{ name: 'systemInfo', label: t('查看系统消息') },
		]
		if (!SWITCH.ops) {
			data = [
				{ name: 'apply', label: t('审批终端申请') },
				{ name: 'systemInfo', label: t('查看系统消息') },
			]
		}
		if (meetingType === 2) {
			data = data.filter((item) => item.name !== 'apply') //RTC会议无审批功能
		}
		update({ tabData: data })
	}, [SWITCH, meetingType])

	useInterval(() => {
		if (isExitChecking) checkingService.run(meetingMoid)
	}, 30000)

	useEffect(() => {
		if (isExitChecking) checkingService.run(meetingMoid)
	}, [isExitChecking])

	const handleClose = () => {
		update({
			showHelper: false,
			tab: 'apply',
		})
	}
	const handleOpen = () => {
		if (showHelper) {
			update({
				showHelper: false,
			})
		} else {
			if (showApplyTip) {
				update({
					showApplyTip: false,
					showHelper: true,
					tab: 'apply',
				})
			} else if (checkingService.list.length > 0) {
				update({
					showHelper: true,
					tab: 'checking',
				})
			} else {
				update({
					showHelper: true,
					tab: meetingType === 2 ? 'checking' : 'apply',
				})
			}
		}
	}

	useEffect(() => {
		if (msgCache.length < 2) {
			setDisable({ pre: true, next: true })
		} else {
			let preShow = disable.pre
			let nextShow = disable.next
			if (msgCache[msgCache.length - 1].index > sysMessage.index) {
				nextShow = false
			} else {
				nextShow = true
			}
			if (msgCache[0].index < sysMessage.index) {
				preShow = false
			} else {
				preShow = true
			}
			setDisable({ pre: preShow, next: nextShow })
		}
	}, [msgCache, sysMessage])

	return (
		<Wrap>
			<ScrollWrap className="notify-scroll">
				<HelpWrap ref={ref}>
					<IconHelper onClick={handleOpen}>
						{(checkingService.list.length > 0 || applyList.length > 0) && <i className="notify-tip"></i>}
					</IconHelper>
				</HelpWrap>
				{showApplyTip && !showHelper && (
					<StyledRequestTip>
						<span className="num">{applyList.length}</span>
						{t('个与会方正在发起申请')}
						<span
							className="detail"
							onClick={() =>
								update({
									showApplyTip: false,
									showHelper: true,
									tab: 'apply',
								})
							}
						>
							{t('查看')}
						</span>
						<IconClose className="close-icon" onClick={() => update({ showApplyTip: false })} />
					</StyledRequestTip>
				)}
				<ScrollBtn
					className={`scroll-btn prev ${disable.pre ? 'disable' : ''}`}
					onClick={() => handleShow(true)}
				></ScrollBtn>
				<ScrollBtn
					className={`scroll-btn next ${disable.next ? 'disable' : ''}`}
					onClick={() => handleShow(false)}
				></ScrollBtn>
			</ScrollWrap>
			<BodyWrap>
				{sysMessage.msg && <span> {t('系统消息：')}</span>}
				{sysMessage.sender && <span className="sender"> {sysMessage.sender} </span>}
				{sysMessage.msg && <span> {sysMessage.msg}</span>}
			</BodyWrap>
			<Modal
				open={showHelper}
				width={574}
				height={400}
				onCancel={handleClose}
				title={t('会议助手')}
				closeIcon={<IconModalRemove onClick={handleClose} />}
				needFooter={false}
				hasBackdrop={false}
				canDrag={true}
				relativePosition={{ relativeRef: ref, placement: 'topStart' }}
			>
				<StyledWrap className="helper-modal">
					<div className="helper-body">
						{tab === 'apply' && <Apply />}
						{tab === 'checking' && <Checking checkingService={checkingService} />}
						{tab === 'systemInfo' && <SystemInfo />}
					</div>
				</StyledWrap>
			</Modal>
		</Wrap>
	)
}
export default Helper
